package com.example.guiguiapplicatio.fragment.examination;

import android.content.Intent;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.navigation.Navigation;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;


import com.example.guiguiapplicatio.api.InsertExaminatiionApi;
import com.example.guiguiapplicatio.api.Interface.AllCallback;

import com.example.guiguiapplicatio.R;
import com.example.guiguiapplicatio.Response.ExaminationAdd;
import com.example.guiguiapplicatio.databinding.FragmentExaminaionEditBinding;
import com.example.guiguiapplicatio.util.ResponseBody;
import com.example.guiguiapplicatio.utils.PathUtils;
import com.google.android.material.bottomnavigation.BottomNavigationView;

import java.io.File;
import java.text.ParseException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;


public class ExaminationEditFragment extends Fragment implements AllCallback {
    FragmentExaminaionEditBinding binding;
    public static final int CHOOSE_PHOTO = 1;
    public static final int STORAGE_PERMISSION = 1;
    private File file = null;
    private InsertExaminatiionApi insertExaminatiionApi;

    private ExaminationAdd examinationAdd = new ExaminationAdd();
    private static final String ARG_ID_CARD = "idCard";
    private static final String NAME = "name";
    private String idCard;
    private String name;
    private CheckBox[] checkBoxes;
    private String lip;
    private String dentalcaries;
    private String pharynx;
    private String hearing;
    private String motion;
    private String fundus;
    private String skin;
    private String zZCheckedText;

    private Map<String, Boolean> zhengZhuangCheck;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            idCard = getArguments().getString(ARG_ID_CARD);
            name = getArguments().getString(NAME);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentExaminaionEditBinding.inflate(inflater, container, false);
        View view = binding.getRoot();
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1; // 月份从 0 开始，所以要加 1
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        String dateString = year + "年" + month + "月" + day + "日";
        binding.dateText.setText(dateString);
        binding.nameText.setText(name);
        insertExaminatiionApi = new InsertExaminatiionApi();
        insertExaminatiionApi.setAllCallback(this);


//        examinationAdd = new ExaminationAdd();
        checkBoxes = new CheckBox[]{
                view.findViewById(R.id.wuzhengzhuang),
                view.findViewById(R.id.toutong),
                view.findViewById(R.id.touyun),
                view.findViewById(R.id.xinji),
                view.findViewById(R.id.xiongmen),
                view.findViewById(R.id.xiongtong),
                view.findViewById(R.id.manxingkesou),
                view.findViewById(R.id.ketan),
                view.findViewById(R.id.huxikunnan),
                view.findViewById(R.id.duoyin),
                view.findViewById(R.id.duoniao),
                view.findViewById(R.id.tizhongxiajiang),
                view.findViewById(R.id.fali),
                view.findViewById(R.id.guanjiezhongtong),
                view.findViewById(R.id.shilimohu),
                view.findViewById(R.id.shoujiaomamu),
                view.findViewById(R.id.niaoji),
                view.findViewById(R.id.niaotong),
                view.findViewById(R.id.bianmi),
                view.findViewById(R.id.fuxie),
                view.findViewById(R.id.exinoutu),
                view.findViewById(R.id.yanhua),
                view.findViewById(R.id.rufangzhangtong),
                view.findViewById(R.id.erming),
                view.findViewById(R.id.qita),

        };
        zhengZhuangCheck = new HashMap<>();
        for (CheckBox checkBox : checkBoxes) {
            String text = checkBox.getText().toString();
            zhengZhuangCheck.put(text, false);
        }

        setExaminationAdd();
        binding.xinImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                xzImage();
            }
        });
//        binding.xinUpload.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (file != null) {
//                    insertExaminatiionApi.performInsertExamination(file);
//                } else {
//                    Toast.makeText(getContext(), "请先选择图片", Toast.LENGTH_SHORT).show();
//                }
//            }
//        });
        binding.uploadBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    publicExaminationComit();
                    Log.d("info", examinationAdd.toString());
                    if (file != null) {
                        insertExaminatiionApi.performInsertExamination(file, examinationAdd);
                    } else {
                        Toast.makeText(getContext(), "请先选择图片", Toast.LENGTH_SHORT).show();
                    }

            }
        });
        binding.comitBtu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    publicExaminationComit();
                    Log.d("info", examinationAdd.toString());
                    if (file != null) {
                        insertExaminatiionApi.performInsertExamination(file, examinationAdd);
                    } else {
                        Toast.makeText(getContext(), "请先选择图片", Toast.LENGTH_SHORT).show();
                    }

            }
        });

        binding.serviceBack.setOnClickListener(Navigation.createNavigateOnClickListener(R.id.action_examinationEditFragment_to_examinationStartFragment));
//        binding.serviceBack.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                NavController navController = Navigation.findNavController(v);
//                navController.popBackStack();
//            }
//        });

        return view;
    }

    public void publicExaminationComit() {
        StringBuilder zZChecked = new StringBuilder();
        for (Map.Entry<String, Boolean> entry : zhengZhuangCheck.entrySet()) {
            if (entry.getValue()) {
                String key = entry.getKey();
                if (key.contains("其他")) {
                    key = binding.qitashuru.getText().toString();
                    if (key.isEmpty()) {
                        key = "其他";
                    }
                }
                if (zZChecked.length() > 0) {
                    zZChecked.append("、");
                }
                zZChecked.append(key);

            }
        }
        if (fundus != null) {
            if (fundus.equals("异常")) {
                fundus = binding.yandiEdit.getText().toString();
                if (fundus.isEmpty()) {
                    fundus = "异常";
                }
            }
        }
        if (skin != null) {
            if (skin.equals("其他")) {
                skin = binding.pifuEdit.getText().toString();
                if (skin.isEmpty()) {
                    skin = "其他";
                }
            }
        }

        zZCheckedText = zZChecked.toString();
        examinationAdd.setIdcard(idCard);
        examinationAdd.setSymptom(zZCheckedText);
        examinationAdd.setLip(lip);
        examinationAdd.setDentalCaries(dentalcaries);
        examinationAdd.setPharynx(pharynx);
        examinationAdd.setHearing(hearing);
        examinationAdd.setMotion(motion);
        examinationAdd.setFundus(fundus);
        examinationAdd.setSkin(skin);

        examinationAdd.setKongfuxuetang(binding.kongfuxuetangEdit.getText().toString());
        examinationAdd.setHeight(binding.shengaoEdit.getText().toString());
        examinationAdd.setTemperature(binding.tiwenEdit.getText().

                toString());
        examinationAdd.setPulseRate(binding.mailvEdit.getText().

                toString());
        examinationAdd.setRespiratoryRate(binding.huxiEdit.getText().

                toString());
        examinationAdd.setLeftPressure(binding.xueyaLeftEdit.getText().

                toString());
        examinationAdd.setRightPressure(binding.xueyaRightEdit.getText().

                toString());
        examinationAdd.setWeight(binding.tizhongEdit.getText().

                toString());
        examinationAdd.setWaist(binding.yaoweiEdit.getText().

                toString());
        examinationAdd.setMbi(binding.bmiEdit.getText().

                toString());
        examinationAdd.setOldHealthy(binding.oldHealthEdit.getText().

                toString());
        examinationAdd.setOldSelfCare(binding.oldZiliEdit.getText().

                toString());
        examinationAdd.setOldCognition(binding.oldRenzhiEdit.getText().

                toString());
        examinationAdd.setOldEmotion(binding.oldQingganEdit.getText().

                toString());
        examinationAdd.setDiet(binding.yinshiEdit.getText().

                toString());
        examinationAdd.setExercise(binding.duanlianEdit.getText().

                toString());
        examinationAdd.setSleep(binding.shuimianEdit.getText().

                toString());
        examinationAdd.setDrink(binding.yinjiuEdit.getText().

                toString());
        examinationAdd.setWork(binding.workEdit.getText().

                toString());
        examinationAdd.setLeftEye(binding.zuoyanEdit.getText().

                toString());
        examinationAdd.setRightEye(binding.youyanEdit.getText().

                toString());
        examinationAdd.setUrineProtein(binding.niaodanbaiEdit.getText().

                toString());
        examinationAdd.setUrinarySugar(binding.niaotangEdit.getText().

                toString());
        examinationAdd.setUrinaryKetoneBody(binding.niaotongtiEdit.getText().

                toString());
        examinationAdd.setUrinaryOccultBlood(binding.niaoqianxueEdit.getText().

                toString());
        examinationAdd.setUrinaryOther(binding.niaoQitaEdit.getText().

                toString());
        examinationAdd.setDiagnosticResults(binding.zhenduanEdit.getText().

                toString());
        examinationAdd.setMicroUrineProtein(binding.niaoWeiliangEdit.getText().

                toString());
        examinationAdd.setFecalOccultBlood(binding.dabianQianxueEdit.getText().

                toString());
        examinationAdd.setGlycosylatedHemoglobin(binding.tangXuedanbaiEdit.getText().

                toString());
        examinationAdd.setHbsag(binding.yigangKangyuanEdit.getText().

                toString());
        examinationAdd.setSerumAlanineAminotransferase(binding.bingzhuanAnEdit.getText().

                toString());
        examinationAdd.setSerumAspartateAminotransferase(binding.caozhuanAnEdit.getText().

                toString());
        examinationAdd.setAlbumin(binding.baidanbaiEdit.getText().

                toString());
        examinationAdd.setTotalBilirubin(binding.zongdanhongsuEdit.getText().

                toString());
    }

    public void setExaminationAdd() {
        //症状复选框选择
        CompoundButton.OnCheckedChangeListener checkBoxListener = new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                String text = buttonView.getText().toString();
                zhengZhuangCheck.put(text, isChecked);
            }
        };
        for (CheckBox checkBox : checkBoxes) {
            checkBox.setOnCheckedChangeListener(checkBoxListener);
        }
        //嘴唇单选框
        binding.zuichunGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                RadioButton radiobutton = group.findViewById(checkedId);
                lip = radiobutton.getText().toString();
            }
        });
        binding.yachiGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                RadioButton radioButton = group.findViewById(checkedId);
                dentalcaries = radioButton.getText().toString();
            }
        });
        binding.yanhouGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                RadioButton radioButton = group.findViewById(checkedId);
                pharynx = radioButton.getText().toString();
            }
        });
        binding.tingliGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                RadioButton radioButton = group.findViewById(checkedId);
                hearing = radioButton.getText().toString();
            }
        });
        binding.yundongGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                RadioButton radioButton = group.findViewById(checkedId);
                motion = radioButton.getText().toString();
            }
        });
        binding.yandiGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                RadioButton radioButton = group.findViewById(checkedId);
                fundus = radioButton.getText().toString();
            }
        });
        binding.pifuGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                RadioButton radioButton = group.findViewById(checkedId);
                skin = radioButton.getText().toString();
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) { // 添加null检查
            switch (requestCode) {
                case CHOOSE_PHOTO:
                    //显示图片
                    if (data.getData() != null) { // 添加null检查
                        binding.xinImg.setImageURI(data.getData());
                        System.out.println("图片在手机上的虚拟路径为：" + data.getData());
                        String realPath = PathUtils.getRealPath(this.getContext(), data);
                        System.out.println("图片在手机上的真实路径为：" + realPath);
                        file = new File(realPath);
                        if (file.exists()) {
                            System.out.println("成功转换为 File 对象");
                        } else {
                            System.out.println("文件不存在，转换失败");
                        }
                    } else {
                        System.out.println("未选择任何照片");
                    }
                    break;
                default:
                    break;
            }
        } else {
            System.out.println("未选择任何图片");
        }
    }


    private void xzImage() {

        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent, CHOOSE_PHOTO); // 打开本地存储
    }


    @Override
    public void onResume() {
        BottomNavigationView bottomNavigationView = requireActivity().findViewById(R.id.nav_view);
        bottomNavigationView.setVisibility(View.INVISIBLE);
        //这两行代码设置隐藏底部导航栏，若要显示啧修改INVISIBLE为Visible（可见）
        super.onResume();
    }

    @Override
    public void onSuccess(ResponseBody<Object> responseBody) throws ParseException {

        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getContext(), "体检提交响应成功", Toast.LENGTH_SHORT).show();
            }
        });


    }

    @Override
    public void onFailure(String errorMessage) {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getContext(), "体检提交响应失败", Toast.LENGTH_SHORT).show();
            }
        });
    }


}